package com.zdf.license.web.controller;

import com.zdf.license.core.model.LicenseExtraParam;
import com.zdf.license.creator.config.LicenseCreatorProperties;
import com.zdf.license.creator.model.LicenseCreatorParam;
import com.zdf.license.creator.service.LicenseCreatorService;
import com.zdf.license.web.pojo.RegisterParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

@CrossOrigin
@Controller
@AllArgsConstructor
public class IndexController {
    private final LicenseCreatorService licenseCreatorService;
    private final LicenseCreatorProperties properties;


    @GetMapping("/")
    public String index(){
        return "index";
    }

    /**
     * 将申请码转化为真实数据
     * @param code 申请吗
     * @return AjaxResult
     */
    @PostMapping("/decode")
    @ResponseBody
    public AjaxResult<?> decodeCode(String code) {
        return AjaxResult.success(licenseCreatorService.decodeCode(code));
    }

    /**
     * 将申请码转化为真实数据
     *
     * @param registerParam 注册参数
     */
    @PostMapping("/generate")
    public void generate(RegisterParam  registerParam, HttpServletRequest request, HttpServletResponse response) throws Exception {
        registerParam.setLicenseAuthParams(getParams(request));
        if (registerParam.getExpiryTime() == null || StringUtils.isEmpty(registerParam.getCode())) {
            throw new RuntimeException("参数异常");
        }
        LicenseExtraParam licenseExtraParam = licenseCreatorService.decodeCode(registerParam.getCode());
        licenseExtraParam.setParams(registerParam.getLicenseAuthParams());
        licenseExtraParam.setIpCheck(registerParam.isIpCheck());
        licenseExtraParam.setMacCheck(registerParam.isMacCheck());
        licenseExtraParam.setCpuCheck(registerParam.isCpuCheck());
        licenseExtraParam.setBoardCheck(registerParam.isBoardCheck());
        LicenseCreatorParam param = properties.buildLicenseCreatorParam();
        param.setExtraParam(licenseExtraParam);
        param.setExpiryTime(registerParam.getExpiryTime());
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        response.addHeader("Access-Control-Expose-Headers", "*");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie, token");
        setAttachmentCoding(request, response, properties.getFilename());
        try (OutputStream os = response.getOutputStream()) {
            os.write(licenseCreatorService.generateLicense(param));
        }
    }

    private void setAttachmentCoding(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            String browser = request.getHeader("User-Agent");
            if (browser.contains("MSIE 6.0") || browser.contains("MSIE 7.0")) { // IE6, IE7 浏览器
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else if (browser.contains("MSIE 8.0")) { // IE8
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (browser.contains("MSIE 9.0")) { // IE9
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (browser.contains("Chrome")) { // 谷歌
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (browser.contains("Safari")) { // 苹果
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else { // 火狐或者其他的浏览器
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.addHeader("content-disposition",
                    "attachment;filename=" + fileName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private Map<String, Object> getParams(HttpServletRequest request){
        Enumeration<String> enumeration = request.getParameterNames();
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            if (name.startsWith("params.")) {
                Object value =  request.getParameter(name);
                name = name.substring("params.".length());
                params.put(name, value);
            }
        }
        return params;
    }
}
